package com.huanzhidadi.single.thread;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorTest {
    public static void main(String[] args) {
        // corePoolSize核心线程数
        // maximumPoolSize最大线程数
        // keepAliveTime线程池中空闲线程等待工作的超时时间，默认只从最大线程数降低到核心线程数，可以通过allowCoreThreadTimeOut(true)降低核心线程数
        // ArrayBlockingQueue等待队列
        // 待执行的线程刚超过核心线程数时，先在等待队列中等待，等待队列满了后，核心线程数逐步增加到最大线程数同步执行
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 10, 1, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(5));
        //threadPoolExecutor.allowCoreThreadTimeOut(true);
        for (int i=0; i<20; i++) {
            /*try {
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            MyTask myTask = new MyTask(i);
            threadPoolExecutor.execute(myTask);
            System.out.println("线程池中活跃线程数目："+threadPoolExecutor.getPoolSize()+"，队列中等待执行的任务数目："+
                    threadPoolExecutor.getQueue().size()+"，已执行完毕的任务数目："+threadPoolExecutor.getCompletedTaskCount());
        }
        while (0 < threadPoolExecutor.getActiveCount()) {
            try {
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程池中活跃线程数目："+threadPoolExecutor.getActiveCount()+"，队列中等待执行的任务数目："+
                    threadPoolExecutor.getQueue().size()+"，已执行完毕的任务数目："+threadPoolExecutor.getCompletedTaskCount());
        }
        threadPoolExecutor.shutdown();
        System.out.println("主线程执行完毕");
    }
}

class MyTask implements Runnable {
    private int taskNum;

    public MyTask(int num) {
        this.taskNum = num;
    }

    @Override
    public void run() {
        System.out.println("正在执行task "+taskNum);
        try {
            Thread.currentThread().sleep(RandomUtil.randomLong(1000, 4000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task "+taskNum+"执行完毕");
    }
}